<script setup name="banner">
import { songDetail } from '@/services/home'
import { formatSongs } from '@/utils/util'
import { usePlayStore } from '@/stores'
import { useRouter } from 'vue-router'

defineProps({
  bannerlist: {
    type: Array
  },
  loading: {
    type: Boolean
  }
})

const playStore = usePlayStore()
const router = useRouter()

const handlePath = async item => {
  switch (item.targetType) {
    // 单曲
    case 1:
      const { privileges, songs } = await songDetail(item.targetId)
      const filteredSongs = formatSongs(songs, privileges)
      // 如果当前播放列表为空
      if (!playStore.playlist.length) {
        playStore.setPlaylist(filteredSongs)
      } else {
        // 查找当前歌曲在播放列表中的位置
        const playlistIndex = playStore.findIndexs(filteredSongs, playStore.playlist)
        // 如果歌曲已经在播放列表中，则设置播放索引为该歌曲的索引
        if (playlistIndex !== -1) {
          // 设置播放索引为该歌曲的索引
          playStore.setPlayIndex(playlistIndex)
        } else {
          // 否则，将歌曲添加到播放列表末尾，并设置播放索引为新添加的歌曲索引
          const newPlayList = playStore.concatPlayList(filteredSongs, playStore.playlist)
          playStore.setPlaylist(newPlayList)
          playStore.setPlayIndex(newPlayList.length - 1)
        }
      }
      // 设置播放状态为开始
      playStore.setPlayStatus(false)
      // 打开音乐详情弹框
      playStore.changeMusicDialog(true)
      break
    case 10:
      router.push({ path: '/album', query: { id: item.targetId } })
      break
    // 歌单
    case 1000:
      router.push({ path: '/playlist', query: { id: item.targetId } })
      break
    // MV
    case 1004:
      router.push({ path: '/mvlist/mv', query: { id: item.targetId } })
      break
  }
}
</script>

<template>
  <van-skeleton v-if="loading">
    <template #template>
      <van-skeleton-image />
    </template>
  </van-skeleton>
  <van-swipe :autoplay="3000" lazy-render indicator-color="white" v-else>
    <van-swipe-item v-for="item in bannerlist" :key="item">
      <van-image width="100%" height="auto" :src="item.imageUrl ? item.imageUrl : item.pic" @click="handlePath(item)" />
    </van-swipe-item>
  </van-swipe>
</template>

<style scoped lang="scss">
.van-swipe-item {
  padding: 2px 10px;

  :deep(.van-image__img) {
    border-radius: 10px;
  }
}

.van-skeleton {
  padding: 0 8px;

  .van-skeleton-image {
    width: 100%;
    height: 140px;
    border-radius: 10px;
  }
}
</style>
